//
//  PageTitleView.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/26.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

class PageTitleView: UIView {

    weak var delegate: PageTitleViewDelegate?
    
    var currentIndex: Int
    
    var style: PageViewStyle
    
    var titles: [String]
    
    init(frame: CGRect, style: PageViewStyle, titles: [String], currentIndex: Int) {
        self.style = style
        self.titles = titles
        self.currentIndex = currentIndex
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        contentView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
        
        layoutTitleLabel()
        layoutUnderline()
    }
    
    private lazy var titleLabels = [UILabel]()
    
    private lazy var contentView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        return view
    }()
    
    private lazy var underline: UIView = {
        let view = UIView()
        view.backgroundColor = style.underlineColor
        view.layer.cornerRadius = style.underlineRadius
        return view
    }()
    
    /// 颜色渐变
    private lazy var normalRGB = self.style.titleNormalColor.getRGB()
    private lazy var selectRGB = self.style.titleSelectedColor.getRGB()
    private lazy var detalRGB: ColorRGB = {
        let r = self.selectRGB.red - self.normalRGB.red
        let g = self.selectRGB.green - self.normalRGB.green
        let b = self.selectRGB.blue - self.normalRGB.blue
        return (r, g, b)
    }()
}

extension PageTitleView {
    private func setupUI() {
        addSubview(contentView)
        setupTitleLabel()
        setupUnderline()
    }
    
    private func setupTitleLabel() {
        for (i, title) in titles.enumerated() {
            let label = UILabel()
            label.tag = i
            label.text = title
            label.textColor = i == currentIndex ? style.titleSelectedColor : style.titleNormalColor
            label.backgroundColor = i == currentIndex ? style.titleViewSelectedColor : .clear
            label.textAlignment = .center
            label.font = style.titleFont
            label.isUserInteractionEnabled = true
            let tap = UITapGestureRecognizer(target: self, action: #selector(tappedTitleLabel(_:)))
            label.addGestureRecognizer(tap)
            contentView.addSubview(label)
            
            titleLabels.append(label)
        }
    }
    
    private func setupUnderline() {
        guard style.isShowUnderline else { return }
        contentView.addSubview(underline)
    }
    
    private func layoutTitleLabel() {
        var x: CGFloat = 0
        let y: CGFloat = style.titleViewY
        var width: CGFloat = 0
        let height: CGFloat = frame.size.height - style.titleViewY
        
        let count = titleLabels.count
        for (i, titleLabel) in titleLabels.enumerated() {
            switch style.titleViewType {
            case .normal:
                width = bounds.width / CGFloat(count)
            case .left:
                width = 110
            }
            x = (width + style.titleMargin) * CGFloat(i) + style.titleMargin
            titleLabel.frame = CGRect(x: x, y: y, width: width, height: height)
        }
        
        if style.isTitleScaleEnabled {
            titleLabels[currentIndex].transform = CGAffineTransform(scaleX: style.titleMaximumScaleFactor,
                                                                    y: style.titleMaximumScaleFactor)
        }
    }
    
    private func layoutUnderline() {
        guard currentIndex < titleLabels.count else { return }
        let label = titleLabels[currentIndex]
        
        let labelTitleWidth = label.text!.width(font: style.titleFont, height: label.frame.height)
        underline.frame.origin.x = label.frame.origin.x + (label.frame.width - labelTitleWidth) / 2
        underline.frame.origin.y = bounds.height - style.underlineHeight
        underline.frame.size.width = labelTitleWidth
        underline.frame.size.height = style.underlineHeight
    }
}

extension PageTitleView {
    @objc private func tappedTitleLabel(_ tap: UITapGestureRecognizer) {
        guard let index = tap.view?.tag else { return }
        selectedTitle(at: index)
    }
}

extension PageTitleView {
    func selectedTitle(at index: Int) {
        if index > titles.count || index < 0 {
            YSGLog("TTPageTitleView - selctedTitle: 数组越界...")
        }
        
        if index == currentIndex {
            delegate?.eventHandleable??.titleViewDidRepeatClicked?()
            return
        }
        
        let sourceLabel = titleLabels[currentIndex]
        let targetLabel = titleLabels[index]
        
        sourceLabel.textColor = style.titleNormalColor
        targetLabel.textColor = style.titleSelectedColor
        
        delegate?.eventHandleable??.contentViewDidDisappear?()
        
        currentIndex = index
        
        // 代理回调
        delegate?.pageTitleView(self, didSelectedAt: currentIndex)
        
        if style.isTitleScaleEnabled {
            UIView.animate(withDuration: 0.25) {
                sourceLabel.transform = CGAffineTransform.identity
                targetLabel.transform = CGAffineTransform(scaleX: self.style.titleMaximumScaleFactor,
                                                          y: self.style.titleMaximumScaleFactor)
            }
        }
        
        if style.isShowUnderline {
            let targetLabelTitleWidth = targetLabel.text!.width(font: style.titleFont, height: targetLabel.bounds.height)
            UIView.animate(withDuration: 0.25) {
                self.underline.frame.origin.x = targetLabel.frame.origin.x + (targetLabel.frame.width - targetLabelTitleWidth) / 2
                self.underline.frame.size.width = targetLabelTitleWidth
            }
        }
    }
    
    private func fixUI(_ targetLabel: UILabel) {
        UIView.animate(withDuration: 0.05) {
            targetLabel.textColor = self.style.titleSelectedColor
            
            if self.style.isTitleScaleEnabled {
                targetLabel.transform = CGAffineTransform(scaleX: self.style.titleMaximumScaleFactor,
                                                          y: self.style.titleMaximumScaleFactor)
            }
            
            if self.style.isShowUnderline {
                let targetLabelTitleWidth = targetLabel.text!.width(font: self.style.titleFont, height: targetLabel.bounds.height)
                self.underline.frame.origin.x = targetLabel.frame.origin.x + (targetLabel.frame.width - targetLabelTitleWidth) / 2
                self.underline.frame.size.width = targetLabelTitleWidth
            }
        }
    }
}

extension PageTitleView: PageContentViewDelegate {
    func pageContentView(_ contentView: PageContentView, didEndScrollAt index: Int) {
        let sourceLabel = titleLabels[currentIndex]
        let targetLabel = titleLabels[index]
        
        sourceLabel.backgroundColor = .clear
        targetLabel.backgroundColor = style.titleViewSelectedColor
        
        currentIndex = index
        
        fixUI(targetLabel)
    }
    
    func pageContentView(_ contentView: PageContentView, scrollingWith sourceIndex: Int, targetIndex: Int, progress: CGFloat) {
        if sourceIndex >= titleLabels.count || sourceIndex < 0 { return }
        if targetIndex >= titleLabels.count || targetIndex < 0 { return }
        
        let sourceLabel = titleLabels[sourceIndex]
        let targetLabel = titleLabels[targetIndex]
        sourceLabel.textColor = UIColor(r: selectRGB.red - progress * detalRGB.red,
                                        g: selectRGB.green - progress * detalRGB.green,
                                        b: selectRGB.blue - progress * detalRGB.blue)
        targetLabel.textColor = UIColor(r: normalRGB.red + progress * detalRGB.red,
                                        g: normalRGB.green + progress * detalRGB.green,
                                        b: normalRGB.blue + progress * detalRGB.blue)
        
        if style.isTitleScaleEnabled {
            let detalScale = style.titleMaximumScaleFactor - 1.0
            sourceLabel.transform = CGAffineTransform(scaleX: style.titleMaximumScaleFactor - progress * detalScale,
                                                      y: style.titleMaximumScaleFactor - progress * detalScale)
            targetLabel.transform = CGAffineTransform(scaleX: 1.0 + progress * detalScale,
                                                      y: 1.0 + progress * detalScale)
        }
        
        if style.isShowUnderline {
            UIView.animate(withDuration: 0.25) {
                self.underline.frame.origin.x = self.underline.frame.origin.x
                self.underline.frame.size.width = self.underline.frame.width
            }
        }
    }
}
